package cool.xiaokang.familyaccount.realm;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cool.xiaokang.familyaccount.dao.ManagerDao;
import cool.xiaokang.familyaccount.dao.MenuDao;
import cool.xiaokang.familyaccount.dao.UserDao;
import cool.xiaokang.familyaccount.pojo.Manager;
import cool.xiaokang.familyaccount.pojo.Menu;
import cool.xiaokang.familyaccount.pojo.User;

/**
 * 
 * @Description: 自定义realm
 * @author 小康
 * @version V1.0.0 2020年1月29日 下午2:35:46
 */
public class familyRealm extends AuthorizingRealm {
	private static final Logger LOGGER = Logger.getRootLogger();
	@Autowired
	private UserDao userDao;

	@Autowired
	private ManagerDao managerDao;

	@Autowired
	private MenuDao menuDao;

	// 认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
		// 获得页面输入的用户名
		String username = passwordToken.getUsername();
		LOGGER.info("当前用户:【" + username + "】,进入familyRealm开始认证");
		// 根据用户名查询数据库中的密码
		User user = userDao.findUserByName(username);
		Manager manager = managerDao.findManagerByName(username);
		if (user != null) {
			AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUser_password(), this.getName());
			return info;
		}
		if (manager != null) {
			AuthenticationInfo info = new SimpleAuthenticationInfo(manager, manager.getManager_pwd(), this.getName());
			return info;
		}
		return null;
	}

	// 授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Manager manager = (Manager) SecurityUtils.getSubject().getPrincipal();
		List<Menu> list = null;
		if (manager.getManager_name().equals("admin")) {
			list = menuDao.findAll();
		}
		if (!manager.getManager_name().equals("admin")) {
			list = menuDao.findByManagerId(manager.getManager_id());
		}
		for (Menu menu : list) {
			info.addStringPermission(menu.getMenu_code());
		}
		return info;
	}
}
